﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace Axiom.Hermetica.WPF.Models
{
	public class ImageService
	{
		private static IDictionary<Guid, byte[]> _images = new Dictionary<Guid, byte[]>();

		public static IDictionary<Guid, byte[]> Images
		{
			get { return ImageService._images; }
		}

		public static ImageSource GetImage(Guid id)
		{
			if (id == Guid.Empty || !_images.ContainsKey(id))
			{
				return null;
			}

			ImageSource result = null;

			using (var ms = new MemoryStream(_images[id]))
			{
				var image = System.Drawing.Image.FromStream(ms);
				image = image.CreateThumb();
				result = image.ToImageSource();
			}

			return result;
		}

		public static void InsertUpdate(Guid id, ImageSource source)
		{
			var image = source as BitmapImage;
			if (id == Guid.Empty || source == null)
			{
				return;
			}
			else if (!_images.ContainsKey(id))
			{
				_images.Add(id, image.ToBytes());
			}
			else if (image != null)
			{
				_images[id] = image.ToBytes();
			}
		}

		public static void Persist()
		{
			var folder = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;

			var path = Path.Combine(folder, "images.dat");

			using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write))
			{
				var bf = new BinaryFormatter();
				bf.Serialize(fs, _images);
			}
		}

		public static void Load()
		{
			var folder = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;

			var path = Path.Combine(folder, "images.dat");

			if (!File.Exists(path))
			{
				return;
			}

			using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
			{
				var bf = new BinaryFormatter();
				_images = bf.Deserialize(fs) as IDictionary<Guid, byte[]>;
			}
		}
	}
}
